import React from 'react';
import BreadcrumbCustom from '../../BreadcrumbCustom';
import locale from 'antd/lib/date-picker/locale/zh_CN';
import { Row, Form, Input, DatePicker, Button, message, Col } from 'antd';
import * as Request from '../../../Server/Upgrade';
import qs from 'qs';
import moment from 'moment';
import * as Const from '../../../common/const';
import { filter } from '../../../common/utils';
import TablePage from "../../TablePage";
require('../../systemManager/customer.css');

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
let defaultPage = { page: Const.DEFAULT_PAGE, size: Const.DEFAULT_PAGE_SIZE };
const format = Const.FMT_SECOND;

class BusinessLog extends React.Component {

    constructor(props) {
        super(props);
        this.state = ({
            defaultRange: [],
            dataSource: [],
            pagination: {},
            loading: true,
            userName: undefined,
            ip: undefined,
        });
    }

    componentWillMount() {
        const now = new Date();
        const start = moment(now, format);
        this.setState({
            defaultRange: [moment(start.format(Const.FMT_MONTH) + '-01 00:00:00', format), moment(now, format)]
        });
    }

    componentDidMount() {
        this.initLogPageData();
    }

    componentWillUnmount() {
        this.setState = () => {
            return;
        };
    }
    search = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                delete values.rangeTime;
                this.setState({ loading: true, ...values });
                this.initLogPageData({ ...defaultPage, ...values });
            }
        });
    }

    reset = () => {
        this.setState({
            userName: undefined,
            ip: undefined,
            loading: true
        });
        this.props.form.setFieldsValue({ ip: undefined, userName: undefined, rangeTime: this.state.defaultRange });
        this.initLogPageData();
    }

    initLogPageData = (params = defaultPage) => {
        const rangeTime = this.props.form.getFieldValue('rangeTime');
        params = { ...params, start: rangeTime[0].format(format), end: rangeTime[1].format(format) }
        Request.systemLog(qs.stringify(params, { filter: filter })).then(res => {
            if (res && Const.REQUEST_SUCCESS == res.code) {
                let data = res.data;
                this.setState({
                    dataSource: data.content,
                    pagination: { ...this.state.pagination, total: data.totalSize, current: data.page + 1, pageSize: params.size },
                    loading: false,
                });
            } else {
                res && res.code !== Const.REQUEST_UNAUTHORIZED && message.error(res.msg);
                this.setState({
                    loading: false
                })
            }
        })
    }

    /* 翻页 */
    handleTableChange = (pagination) => {
        const _this = this;
        const pager = { ..._this.state.pagination };
        pager.current = pagination.current;
        pager.pageSize = pagination.pageSize;
        defaultPage.size = pagination.pageSize;
        _this.setState({
            pagination: pager,
            loading: true
        });
        _this.initLogPageData({
            page: pagination.current - 1,//后台分页默认从第0页开始
            size: pagination.pageSize,
            userName: _this.state.userName,
            ip: _this.state.ip
        });
    }
    disabledDate = (currentDate) => {
        const now = this.state.defaultRange[1];
        return now.format(format) < currentDate.format(format);
    }
    validatorRangeTime = (rule, value, callback) => {
        if (!value || !value.length) {
            callback();
            return;
        }
        const [start, end] = value;
        if (start.month() !== end.month()) {
            callback('不允许跨月查询数据');
        } else {
            callback();
        }
    }
    render() {
        const columns = [
            {
                title: "时间",
                dataIndex: "recordTime",
                width: '16.66%',
                align: 'center',
                render: (text) => moment(text).format('YYYY-MM-DD HH:mm:ss')
            },
            {
                title: "用户名",
                dataIndex: "userName",
                width: '16.66%',
                align: 'center',
            },
            {
                title: "登录IP",
                dataIndex: "ip",
                width: '16.66%',
                align: 'center',
            },
            {
                title: "操作内容",
                dataIndex: "operateContent",
                width: '16.66%',
                align: 'center',
            },
            {
                title: "URI",
                dataIndex: "uri",
                width: '16.66%',
                align: 'center',
            },
            {
                title: "操作结果",
                dataIndex: "result",
                width: '16.66%',
                align: 'center',
                render: (text) => {
                    if (!text) {
                        return <span>成功</span>;
                    } else {
                        return <span style={{ color: 'red' }}>失败</span>;
                    }
                }
            },
            /*{
                title: "原因",
                dataIndex: "reason",
                width: '20%',
                align: 'center',
            }*/
        ];
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 10 },
                md: 9,
                lg: 6,
                xl: 5
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 14 },
                md: 15,
                lg: 18,
                xl: 19
            },
        };

        const timeLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 4 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 20 },
            },
        };

        return (
            <div>
                <BreadcrumbCustom first={'用户操作日志'} />
                <div>
                    <Row>
                        <Form onSubmit={this.search}>
                            <Col span={5}>
                                <FormItem
                                    {...formItemLayout}
                                    label={'用户名:'}
                                >
                                    {getFieldDecorator('userName', {
                                        initialValue: this.state.userName,
                                    })(
                                        <Input maxLength={255} />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={5}>
                                <FormItem
                                    {...timeLayout}
                                    label={'IP:'}
                                >
                                    {getFieldDecorator('ip', {
                                        initialValue: this.state.ip,
                                    })(
                                        <Input maxLength={255} />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={9}>
                                <FormItem
                                    {...timeLayout}
                                    label={'时 间:'}
                                >
                                    {getFieldDecorator('rangeTime', {
                                        rules: [{
                                            validator: this.validatorRangeTime
                                        }],
                                        initialValue: this.state.defaultRange.length && this.state.defaultRange,
                                    })(
                                        <RangePicker
                                            style={{width: '100%' }}
                                            placeholder={['开始日期', '结束日期']}
                                            format={format}
                                            showTime={{ format: 'HH:mm:ss' }}
                                            allowClear={false}
                                            locale={locale}
                                            disabledDate={this.disabledDate}
                                        />
                                    )}
                                </FormItem>
                            </Col>
                            <Col {...Const.BUTTONSPAN} style={{ textAlign: 'center'}}>
                                <FormItem >
                                    <Button
                                        type="primary"
                                        htmlType="submit"
                                    >查询</Button>
                                    <Button
                                        type="default"
                                        onClick={this.reset}
                                    >重置</Button>
                                </FormItem>
                            </Col>
                        </Form>
                    </Row>
                    <Row>
                        <TablePage
                            dataSource={this.state.dataSource}
                            columns={columns}
                            loading={this.state.loading}
                            style={{ paddingTop: 10 }}
                            rowKey={record => record.id}
                            pagination={this.state.pagination}
                            onChange={this.handleTableChange}
                        />
                    </Row>
                </div>
            </div>
        );
    }
}

const BusinessLogForm = Form.create()(BusinessLog);
export default BusinessLogForm;